package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.qianniu.napi.admin.entity.Feedback;
import com.qianniu.napi.admin.entity.JsonDO;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.service.IFeedbackService;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.common.util.ObjectUtil;
import nl.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-04
 */
@RestController
public class FeedbackController {

    private static final Logger logger = LoggerFactory.getLogger(FeedbackController.class);

    @Autowired
    private IFeedbackService feedbackService;
    @Autowired
    private IRedisService redisService;

    @RequestMapping("/api/feedback/list")
    @ResponseBody
    public JsonDO list(@RequestParam(value = "ptype", required = false) String ptype,
                       HttpServletRequest req) {
        JsonDO json = new JsonDO();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("mid", req.getSession().getAttribute("mid"));
        map.put("state", 1);

        List<Feedback> list = feedbackService.selectByMap(map);
        json.setData(list);
        return json;
    }

    @RequestMapping("/api/feedback/add")  //  1(背熟)、网络接口定义：
    @ResponseBody
    //  2、JAVA 方法定义（背熟）：public Jieguo fangfaming([参数类型 canhsu1,参数类型 canhsu2]){ Jieguo jg = new Jieguo();//处理数据  // return jg; }
    public JsonDO feedbackAdd(Feedback feedback, HttpServletRequest req) {

        logger.debug("----------------------------------api/feedback/add  jie kou  kaishi ");
        logger.debug("-----------------------------------tijiao yuanshi neirong feedback="+ JSON.toJSONString(feedback));
        // 3(背熟)、数据对象实例化（变量定义）
        // js: var jsn = new Date();
        // 简单js类型：js: var beizhu = "这是备注信息",jine=100 ;
        JsonDO jsn = new JsonDO();
        User user = redisService.getUser();

        // 4、字段赋值
        feedback.setUid(ObjectUtil.getUid());
        feedback.setMid(ObjectUtil.getMid());
        feedback.setMpid(ObjectUtil.getMpid());

        feedback.setCreatetime(new Date());



        String ip = ObjectUtil.getIP();
        feedback.setIp(ip);// 赋值：  js: feedback.ip = ip
        feedback.setState(1);

        UserAgent userAgent = UserAgent.parseUserAgentString(req.getHeader("User-Agent"));
        feedback.setTerminal(userAgent.getOperatingSystem().toString());

        feedback.setNickname(user.getNickName());
        feedback.setHeadimg(user.getAvatarPic());
        User fduser = redisService.getUser(feedback.getStaffid());
        feedback.setSid(fduser.getSid());
        logger.debug("-----------------------------------fuzhi baocun neirong feedback="+ JSON.toJSONString(feedback));

        // 5(背熟)、保存数据
        feedback.insert();

        if (feedback.getStaffid() != null && feedback.getXing() != null) {
            //查询
            Feedback fd = feedbackService.selectOne(new EntityWrapper<Feedback>()
                    .setSqlSelect("avg(xing) xing")
                    .eq("staffid", feedback.getStaffid())
                    .isNotNull("xing")
            );

            //更新用户五星评价结果
            if (fd != null && fd.getXing() != null) {
                User nuser = new User();
                nuser.setId(feedback.getStaffid());//重点

                nuser.setXing(feedback.getXing());

                nuser.setModifytime(new Date());

                nuser.updateById();//更新动作
            }

        }

        jsn.setInfo("终于卡看懂Java程序怎么运行");
        // 6(背熟)、返回处理结果
        return jsn;// 7(背熟)、js里返回类型无要求
    }

    @RequestMapping("/api/feedback/modify")
    @ResponseBody
    public JsonDO feedbackUpdate(@Valid Feedback feedback,
                                 BindingResult bindingResult, HttpServletRequest req) {
        JsonDO json = new JsonDO();
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            json.setMsg("There are errors! " + bindingResult);
            json.setCode(400);
            return json;
        }
        feedback.updateById();
        return json;
    }

    @RequestMapping("/api/feedback/detail")
    @ResponseBody
    public JsonDO getFeedbackDetailById(@RequestParam("token") String token,
                                        @RequestParam("id") long id, HttpServletRequest req
    ) {
        JsonDO json = new JsonDO();
        Feedback feedback = feedbackService.selectById(id);
        json.setData(feedback);
        return json;
    }

}
